from datetime import date

from core.models import subject
from .models.user_role_assignment import UserRoleAssignment
from .models.classinfo import ClassInfo
from .models.semester import Semester
from .models.grade import Grade

def unread_notifications(request):
    if request.user.is_authenticated:
        return {'unread_notification_count': request.user.received_notifications.filter(is_read=False).count()}
    return {}


def user_roles_and_classes(request):
    context = {}
    if request.user.is_authenticated:
        try:
            # 获取当前学期（示例逻辑，根据实际业务调整）
            current_semester = Semester.objects.filter(start_date__lte=date.today(), end_date__gte=date.today()).first()
            
            # 获取用户当前学期的活跃角色
            if current_semester:
                role_assignments = UserRoleAssignment.objects.filter(user=request.user, semester=current_semester, is_active=True)
                context['user_roles'] = [assignment.role for assignment in role_assignments]
                
                # 获取用户作为班主任的班级（当前学期）
                context['homeroom_classes'] = ClassInfo.objects.filter(homeroom_teacher=request.user, semester=current_semester)
                class_ids = ClassInfo.objects.filter(homeroom_teacher=request.user, semester=current_semester).values_list('id', flat=True)
                context['CLASS_ID'] = class_ids.first() if class_ids else None
                
                # 获取用户所带的班级（当前学期）
                context['TA_CLASS'] = ClassInfo.objects.filter(homeroom_teacher=request.user, semester=current_semester).first()
                
                # 获取当前学科
                from .models.teacher_subject_assignment import TeacherSubjectAssignment
                subject_ids = TeacherSubjectAssignment.objects.filter(teacher=request.user, semester=current_semester).values_list('subject_id', flat=True)
                context['CURRENT_SUBJECT_ID'] = subject_ids.first() if subject_ids else None
                
                if context['CURRENT_SUBJECT_ID']:
                    try:
                        context['CURRENT_SUBJECT'] = subject.Subject.objects.get(id=context['CURRENT_SUBJECT_ID'])
                    except subject.Subject.DoesNotExist:
                        context['CURRENT_SUBJECT'] = None
                        context['CURRENT_SUBJECT_ID'] = None
            
            # 获取当前用户所在的年级
            grade_ids = Grade.objects.filter(grade_leader=request.user).values_list('id', flat=True)
            context['CURRENT_GRADE_ID'] = grade_ids.first() if grade_ids else None
            
        except Exception as e:
            # 记录异常信息
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Error in user_roles_and_classes: {str(e)}")
            # 出现异常时确保返回有效上下文
            pass
    
    return context